var express = require('express');
var router = express.Router();
var mysql = require('../model/mysql');

var model =new  mysql('users')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 注册接口
router.post('/regist', function(req, res, next){
  var data = {
    username: req.body.username,
    password: req.body.password
  }
  // 插入数据库之前需要验证数据...
  model.insert(data,function(err, results) {    
      if (err){
        console.log('注册失败')
        res.redirect('/regist')
      }else{
        console.log('注册成功')
        res.redirect('/login')
      }
  })
})

router.post('/login', function(req, res, next) {
  var data = [req.body.username, req.body.password]
  // 需要有数据校验
  model.field('username').where("username=? and password=?").select(data,function(err, results) {    
      if (err || results.length <= 0){
        console.log('登录失败')
        res.redirect('/login')
      }else{
        // 登录成功
        //var res = JSON.parse(JSON.stringify(results));
        //console.log(results)
        console.log(results[0].username + "登录成功");//req.session.username = data.username // 保存到session
        res.redirect('/')
        
      }    
  })
})

module.exports = router;
